<template>
	<view class="wrap">
		<template v-if="logged">
			<view class="cartGoodsList u-p-b-80" v-if="goodsList.length">
				<u-checkbox-group v-model="checkList" placement="column" @change="checkChange">
					<view class="cartGoods u-flex u-p-15" v-for="(item,index) in goodsList" :key="index">
						<u-checkbox :checked="item.is_checked?true:false" size="20" :name='item.id' shape="square">
						</u-checkbox>
						<view class="goodsInfo u-flex u-p-10">
							<view @click="details(item.goods_id)">
								<u-image border-radius="15" width="200rpx" height="200rpx" :src="item.goods.cover_url">
								</u-image>
							</view>
							<view class="goodsBaseInfo u-flex u-row-between u-col-top u-p-10">
								<view class="priceNum" @click="details(item.goods_id)">
									<text class="title u-p-l-10 u-font-32">{{item.goods.title}}</text>
									<br>
									<text class="small">{{item.goods.description}}</text>
									<view class="u-text-right small">
										库存:<text style="color:red">{{item.goods.stock}}</text>
									</view>
								</view>
								<view class="priceNum u-flex u-row-between">
									<text class="price u-font-34">￥{{item.goods.price}}</text>
									<u-number-box v-model="item.num" :min="0" :max="item.goods.stock" integer
										:name="item.id" @change="numChange">
									</u-number-box>
									<u-icon @click="remove(item.id)" name="trash" color="#e83333" size="36">
									</u-icon>
								</view>
							</view>
						</view>
					</view>
				</u-checkbox-group>
			</view>
			<view class="empty" v-else>
				<u-empty text="购物车空空如也" mode="car"></u-empty>
			</view>
			<view class="bottomFixed u-flex u-p-15">
				<view class="u-flex-3">
					<u-checkbox-group placement="column" @change="allCheckChange">
						<u-checkbox :checked="allCheck" size="20" name="all" shape="circle" label="全选"></u-checkbox>
					</u-checkbox-group>
				</view>
				<view class="u-flex u-flex-7 u-row-around">
					<view>
						<text class="title">合计:</text>
						<text class="price">￥{{totalPrice}}</text>
					</view>
					<u-button type="primary" shape="square" :disabled="!disabled" @click="order">结算订单</u-button>
				</view>
			</view>
		</template>
		<template v-else>
			<u-empty mode="permission" text="请登录后查看"></u-empty>
		</template>
	</view>
</template>

<script>
	let access_token;
	export default {
		data() {
			return {
				goodsList: [],
				logged: false,
				checkList: [],
			}
		},
		onLoad() {
			access_token = uni.getStorageSync('access_token');
			if (access_token) {
				this.logged = true;
			}
		},
		onShow() {
			this.getData();
		},
		computed: {
			//全选和全不选
			allCheck: {
				get() {//初始化时，会执行get方法，根据商品是否全选中，来实现全选复选框的初始选择状态
					return this.goodsList.every((goods) => {
						return goods.is_checked
					})
				},
				set(val) {
					// 准备获取各个购物车id参数
					let idArr = []
					if (val) {
						//说明是设置全选（就是由全不选变为全选）
						//遍历goodsList，把所有 的购物车ID push到idArr中。
						this.goodsList.forEach((goods) => {
							idArr.push(goods.id)
						})
					} else {
						//说明是设置全不选（就是由全选变为全不选）
						//将idArr置空
						idArr = [];
					}
					//接下为调用接口，执行实际的操作
					this.checkChange(idArr);
				}
			},
			//选中商品的总价
			totalPrice() {
				return this.goodsList.filter((goods) => { //过滤掉没有选中商品
					if (goods.is_checked) {						
						return true
					}
				}).reduce((pre, goods) => { //价格累加
					return parseInt(pre) + parseInt(goods.goods.price) * goods.num //乘商品数量
				}, 0);
			},
			//结算按钮是否可用
			disabled(){
				return this.goodsList.some((goods)=>{
					if(goods.is_checked){
						return true;
					}
				})
			}
		},
		methods: {
			async checkChange(e) {
				await uni.$u.http.post(`/api/carts/checked`, {
					_method: 'PATCH',
					cart_ids: e
				}, {
					header: {
						Authorization: 'bearer ' + access_token
					}
				});
				this.getData();
			},
			async numChange(e) {
				const {
					value,
					name
				} = e
				await uni.$u.http.put(`/api/carts/${name}`, {
					num: value
				}, {
					header: {
						Authorization: 'bearer ' + access_token
					}
				});
			},
			async getData() {
				const res = await uni.$u.http.get(`/api/carts`, {
					params: {
						include: 'goods'
					},
					header: {
						Authorization: 'bearer ' + access_token
					}
				});
				//console.log(res);
				this.goodsList = res.data;
			},
			async remove(id) {
				await uni.$u.http.delete(`/api/carts/${id}`, {}, {
					header: {
						Authorization: 'bearer ' + access_token
					}
				})
				uni.$u.toast('移除购物车成功');
				this.getData();//重新刷新购物车
			},
			allCheckChange(e){
				if(e.length){
					this.allCheck = true;
				}
				else{
					this.allCheck = false;
				}
			},
			details(id){
				/* uni.$u.route({
					type:'navigateTo',//此为默认值，可以不写
					url:'/pages/goods/details',
					params:{
						id:id
					}
				}) */
				//如果是navigateTo方式跳转，可以简写为：
				uni.$u.route('/pages/goods/details',{id:id});
			},
			order(){
				uni.$u.route('/pages/cart/order');
			}
		}
	}
</script>

<style scoped lang="scss">
	.wrap {
		min-height: 80vh;

		.empty {
			height: 80vh;
		}

		.loading {
			text-align: center;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
		}

		.title,
		.price {
			font-weight: 800;
		}

		.price {
			color: #e83333;
		}

		.cartGoodsList {
			.cartGoods {
				.goodsInfo {
					width: 100%;
					background-color: rgb(251, 250, 251);

					.goodsBaseInfo {
						width: 100%;
						height: 200rpx;
						flex-direction: column;

						.priceNum {
							width: 100%;

						}
					}
				}
			}
		}

		.bottomFixed {
			position: fixed;
			left: 0;
			right: 0;
			background-color: #fff;
		}

		/*#ifdef H5*/
		.bottomFixed {
			bottom: 90rpx; //tabbar的高度
		}

		/*#endif*/
		/*#ifdef MP-WEIXIN*/
		.bottomFixed {
			bottom: 0;
			z-index: 99999;
		}

		/*#endif*/

	}
</style>
